﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DisposeFinalizeExercise
{
    class BufferedConsole : IDisposable
    {
        StringBuilder buffer;
        int size;

        public BufferedConsole(int size)
        {
            this.size = size;
            this.buffer = new StringBuilder(this.size);
        }

        ~BufferedConsole()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        public void Write(string output)
        {
            foreach (char c in output)
            {
                this.buffer.Append(c);
                if (buffer.Length > this.size)
                {
                    Console.WriteLine(this.buffer);
                    this.buffer.Clear();
                }
            }
        }
        
        public void Dispose(bool disposing)
        {
            Console.WriteLine(this.buffer);
            if (disposing)
            {
                this.buffer = null;
            }
        }

        public void Dispose()
        {
            Dispose(true);
        }
    }
}
